using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 页面仓储实现
    /// 提供页面数据访问操作的完整实现，包括层级结构管理和搜索功能
    /// </summary>
    public class PageRepository : Repository<Page>, IPageRepository
    {
        public PageRepository(LowCodeDbContext context) : base(context)
        {
        }

        /// <summary>
        /// 获取所有页面记录
        /// </summary>
        async Task<IEnumerable<Page>> IPageRepository.GetAllAsync()
        {
            return await _context.Pages
                .Include(p => p.Parent)
                .Include(p => p.Children)
                .Include(p => p.Template)
                .Include(p => p.Creator)
                .OrderBy(p => p.SortOrder)
                .ThenBy(p => p.Title)
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取页面记录
        /// </summary>
        public async Task<Page?> GetByIdAsync(long id)
        {
            return await _context.Pages
                .Include(p => p.Parent)
                .Include(p => p.Children)
                .Include(p => p.Template)
                .Include(p => p.Creator)
                .FirstOrDefaultAsync(p => p.Id == id);
        }

        /// <summary>
        /// 根据别名获取页面记录
        /// </summary>
        public async Task<Page?> GetBySlugAsync(string slug)
        {
            return await _context.Pages
                .Include(p => p.Parent)
                .Include(p => p.Children)
                .Include(p => p.Template)
                .Include(p => p.Creator)
                .FirstOrDefaultAsync(p => p.Slug == slug && p.Status == 1);
        }

        /// <summary>
        /// 获取子页面列表
        /// </summary>
        public async Task<IEnumerable<Page>> GetChildrenAsync(long parentId)
        {
            return await _context.Pages
                .Include(p => p.Parent)
                .Include(p => p.Children)
                .Include(p => p.Template)
                .Where(p => p.ParentId == parentId && p.Status == 1)
                .OrderBy(p => p.SortOrder)
                .ThenBy(p => p.Title)
                .ToListAsync();
        }

        /// <summary>
        /// 获取导航页面
        /// </summary>
        public async Task<IEnumerable<Page>> GetNavigationPagesAsync()
        {
            return await _context.Pages
                .Include(p => p.Parent)
                .Include(p => p.Children)
                .Where(p => p.ShowInNavigation == true && p.Status == 1)
                .OrderBy(p => p.SortOrder)
                .ThenBy(p => p.Title)
                .ToListAsync();
        }

        /// <summary>
        /// 分页获取页面列表
        /// </summary>
        public async Task<(IEnumerable<Page> Items, int TotalCount)> GetPagedAsync(int pageIndex, int pageSize, string? keyword = null, byte? status = null)
        {
            var query = _context.Pages
                .Include(p => p.Parent)
                .Include(p => p.Template)
                .Include(p => p.Creator)
                .AsQueryable();

            if (!string.IsNullOrWhiteSpace(keyword))
            {
                query = query.Where(p => p.Title.Contains(keyword) || 
                                        (p.Content != null && p.Content.Contains(keyword)) ||
                                        (p.Description != null && p.Description.Contains(keyword)));
            }

            if (status.HasValue)
            {
                query = query.Where(p => p.Status == status.Value);
            }

            var total = await query.CountAsync();

            var items = await query
                .OrderBy(p => p.SortOrder)
                .ThenByDescending(p => p.CreatedAt)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (items, total);
        }

        /// <summary>
        /// 添加新页面
        /// </summary>
        async Task IPageRepository.AddAsync(Page entity)
        {
            entity.CreatedAt = DateTime.UtcNow;
            entity.UpdatedAt = DateTime.UtcNow;
            await _context.Pages.AddAsync(entity);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 更新页面信息
        /// </summary>
        async Task IPageRepository.UpdateAsync(Page entity)
        {
            entity.UpdatedAt = DateTime.UtcNow;
            _context.Pages.Update(entity);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除页面
        /// </summary>
        public async Task DeleteAsync(long id)
        {
            var entity = await _context.Pages.FindAsync(id);
            if (entity != null)
            {
                _context.Pages.Remove(entity);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 批量删除页面
        /// </summary>
        public async Task<int> BatchDeleteAsync(IEnumerable<long> ids)
        {
            var pages = await _context.Pages
                .Where(p => ids.Contains(p.Id))
                .ToListAsync();

            _context.Pages.RemoveRange(pages);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 增加页面访问量
        /// </summary>
        public async Task<bool> IncrementViewCountAsync(long id)
        {
            var page = await _context.Pages.FindAsync(id);
            if (page != null)
            {
                page.ViewCount++;
                page.UpdatedAt = DateTime.UtcNow;
                await _context.SaveChangesAsync();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 检查页面别名是否存在
        /// </summary>
        public async Task<bool> SlugExistsAsync(string slug, long? excludeId = null)
        {
            var query = _context.Pages.Where(p => p.Slug == slug);
            
            if (excludeId.HasValue)
                query = query.Where(p => p.Id != excludeId.Value);

            return await query.AnyAsync();
        }

        /// <summary>
        /// 获取页面层级结构
        /// </summary>
        public async Task<IEnumerable<Page>> GetHierarchyAsync()
        {
            return await _context.Pages
                .Include(p => p.Parent)
                .Include(p => p.Children)
                .Include(p => p.Template)
                .Where(p => p.Status == 1)
                .OrderBy(p => p.SortOrder)
                .ThenBy(p => p.Title)
                .ToListAsync();
        }
    }
}
